package com.haizhi.util;


import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.spec.SecretKeySpec;



/**
 * Hello world!
 *
 */
public class MyAES {
	/**
	 * 
	 * jiangjintai
	 * 2016年5月9日
	 * @param content 加密内容
	 * @param password 加密密钥
	 * @return 十六进制密文
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws UnsupportedEncodingException
	 * @throws InvalidKeyException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 */
	public static String encrypt(String content,String password) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		// 判断Key是否为16位
        if (password.length() >16) {
            throw new PasswordOverFlowException();//密码大于16位抛出异常
        }
        
        StringBuffer sb = new StringBuffer(password);
        while(sb.length()!=16){
        	sb.append("j");
        }
		System.out.println(sb);
		
		SecretKeySpec skeySpec = new SecretKeySpec(sb.toString().getBytes("utf-8"), "AES");//构造密钥空间
		Cipher cipher = Cipher.getInstance("AES");//创建密码器
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);// 初始化,这里的模式不一样，要注意
		byte[] byteContent = content.getBytes("utf-8");
		byte[] result = cipher.doFinal(byteContent);  //返回字节数组
		return parseByte2HexStr(result);
	}
	
	/**
	 * 解密
	 * jiangjintai
	 * 2016年5月9日
	 * @param token 密文
	 * @param password 密钥
	 * @return 返回原文
	 * @throws Exception
	 */
	 // 解密
    public static String decrypt(String token, String password) throws Exception {
            // 判断Key是否大于16位
            if (password.length() >16) {
            	throw new PasswordOverFlowException();
            }
            StringBuffer sb = new StringBuffer(password);
            while(sb.length()!=16){
            	sb.append("j");
            }
    		System.out.println(sb);
            SecretKeySpec skeySpec = new SecretKeySpec(sb.toString().getBytes("utf-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);//这里的模式不一样要注意
            byte[] original = cipher.doFinal(parseHexStr2Byte(token));
            String originalString = new String(original,"utf-8");
            return originalString;
           
      
    }

	
	/**将16进制转换为二进制 
	 * @param hexStr 
	 * @return 
	 */  
	private static byte[] parseHexStr2Byte(String hexStr) {  
	        if (hexStr.length() < 1)  
	                return null;  
	        byte[] result = new byte[hexStr.length()/2];  
	        for (int i = 0;i< hexStr.length()/2; i++) {  
	                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
	                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
	                result[i] = (byte) (high * 16 + low);  
	        }  
	        return result;  
	}  
	
	/**将二进制转换成16进制 
	 * @param buf 
	 * @return 
	 */  
	private static String parseByte2HexStr(byte buf[]) {  
	        StringBuffer sb = new StringBuffer();  
	        for (int i = 0; i < buf.length; i++) {  
	                String hex = Integer.toHexString(buf[i] & 0xFF);  
	                if (hex.length() == 1) {  
	                        hex = '0' + hex;  
	                }  
	                sb.append(hex.toUpperCase());  
	        }  
	        return sb.toString();  
	}  
	
}
